package com.elitel.common.auth.filter;


import com.alibaba.fastjson.JSON;
import com.elitel.common.auth.AuthProperties;
import com.elitel.common.core.constant.SysUserConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 系统登录过滤器
 */
@Component
@ConditionalOnProperty(prefix = "auth.local-login", name = "enabled", havingValue = "true")
@WebFilter(urlPatterns = "/*")
public class SysLoginFilter implements Filter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(SysLoginFilter.class);

    @Resource
    private AuthProperties sysFilterProp;

    // 匹配路径工具类
    private Pattern pattern;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化匹配路径工具类
        pattern = Pattern.compile(sysFilterProp.getRegExcludeUrl());
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession(false);
        String verifyFieldValue = session != null ? (String) session.getAttribute(SysUserConstant.LOGIN_ACCOUNT) : null;

        // 非拦截路径 不拦截
        if (pattern.matcher(request.getRequestURI()).find() || (verifyFieldValue!=null && !verifyFieldValue.isEmpty())) {
            filterChain.doFilter(request, response);
            return;
        }


        String xRequestedWith = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            Map<String, Object> resultMap = new HashMap<>(3);
            resultMap.put("code", 401);
            resultMap.put("success", false);
            resultMap.put("msg", "请登录");
            out.write(JSON.toJSONString(resultMap));
            out.flush();
            out.close();
        } else {
            String urlToRedirectTo = sysFilterProp.getLoginPage();
            logger.debug("Constructed service url: {}", urlToRedirectTo);
            logger.debug("redirecting to \"{}\"", urlToRedirectTo);
            response.sendRedirect(urlToRedirectTo);
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public int getOrder() {
        return 4;
    }
}
